<template>
  <div class="addDiary">
    <el-backtop></el-backtop>
    <el-input v-model="diary.title"
    :readonly="writeFlag"
     placeholder="这里是标题..." style="width: 600px;margin-left: 10px;">
    </el-input>
    <hr></hr>
    <el-input v-model="diary.content"
    :readonly="writeFlag"
    placeholder="请在此输入日记内容..."
    clearable :autosize="{ minRows: 10, maxRows: 50}"
      maxlength="5000" show-word-limit type="textarea">
    </el-input>

    <div>
        <el-upload style="margin-top: 20px;"
            :before-upload="beforeAlbumUpload"
            :on-success="handleAlbumSuccess"
            :show-file-list="false"
            :data="imgDid"
            accept="image/*"
            action="http://oneday.vaiwan.com/public/file"
            class="avatar-uploader"
            name="file">
            <img :src="imageUrl" alt="上传图片" class="avatar" style="width: 300px;" v-if="imageUrl">
            <i class="el-icon-plus avatar-uploader-icon" v-else></i>
        </el-upload>
    </div>


    <el-button @click = "saveDiary"
    :disabled="writeFlag"
    style="margin-top: 20px;margin-left: 60px;">保存修改</el-button>
    <el-button @click = "postDiary"
     :disabled="writeFlag"
     style="margin-top: 20px;">发表日记</el-button>
    <el-button @click = "cancleEdit" style="margin-top: 20px;margin-right: 60px;">放弃修改</el-button>
  </div>
</template>

<script>
  import axios from 'axios'
  import Write from './Timeline.vue'
  import Login from '../Jun/Login.vue'

  export default {
    data(){
      return{
        imgDid:{did:''},
        imageUrl:'',
        writeFlag:'',
        this_id:'',
        uid:'',
        diary:{
          title:"",
          content:"",
          editTime:"",
          uid:"",
          state:"",
          did:""
        }
      }
    },

    created(){
      this.selInformation();
    },

    mounted: function(){

    },

    methods:{
      cancleEdit(){
        this.$router.go(-1);
      },
      saveDiary(){
        var _this = this;
        var token = localStorage.getItem("token");
        //向后端发送数据，存草稿箱，进入draft
        axios.post('http://oneday.vaiwan.com/diary/draft', {
          title: this.$data.diary.title,
          content: this.$data.diary.content,
          uid:_this.uid,
          did:_this.diary.did,
            },{headers:{
          token:`${token}`},
          })
            .then(function(response){
              //成功时返回response数据
              /*
              did:""
              state:"1"
              eiditTime:""
              */
             _this.diary.did = response.data.did;
             _this.diary.state = response.data.state;
             alert("保存成功！");
             _this.$router.replace("/drafts");
            })
            .catch(function(error){
              alert("请重新登录！");
              _this.$router.push("/");
            });
      },
      postDiary(){
        var _this = this;
        var token = localStorage.getItem("token");
        if(this.$data.diary.title == "" || this.$data.diary.content == ""){
          alert("标题与正文不能为空！")
        }else{
          //向后端发送数据，进入已发表列表，接口为publish
          axios.post('http://oneday.vaiwan.com/diary/publish', {
            title: this.$data.diary.title,
            content: this.$data.diary.content,
            uid:_this.uid,
            did:_this.diary.did
              },{headers:{
          token:`${token}`},
          })
              .then(function(response){
                //成功时返回response数据
                /*
                did:""
                state:"2"
                eiditTime:""
                */
               _this.diary.did = response.data.did;
               _this.diary.state = response.data.state;
               alert("发表成功！");
               _this.$router.replace("/timeline");
              })
              .catch(function(error){
                alert("请重新登录！");
                _this.$router.push("/");
              });
        }
      },
      selInformation(){
        var _this = this;
        _this.uid = localStorage.getItem('user_id');
        var token = localStorage.getItem("token");
      	//获取传递过来的id和state和文章作者id
      	var did = this.$route.query.did;
        var state = this.$route.query.state;
        var this_id = this.$route.query.this_id;
        //判断传过来的本文作者id是不是该登录用户的uid，是则设writeFlag为false，可编辑文章，若this_id为空则为新建文章，可编辑
        if(this.uid == this_id || this_id == undefined){
          _this.writeFlag = false;
        }else if(this.uid != this_id){ //收到了作者id且不是uid，是好友文章，设writeFlag为true，不可编辑
          _this.writeFlag = true;
        }

        _this.diary.did = did;
        _this.diary.state = state;
        //alert("did: " + _this.diary.did + "state: " + _this.diary.state)  //测试用，正式确定后可以删除

        //如果不是新建日记，则did和state不是默认0或空值，向后端发送请求查询该文章信息
        if(did != undefined && state != undefined){
      	//根据id来查询数据，只需要当前文章的内容，故进入get接口
      	axios.post('http://oneday.vaiwan.com/diary/get', {
          did:_this.diary.did
      	    },{headers:{
          token:`${token}`},
          }).then(function(response){
          //将从后端拿过来的title和content填入当前页面
          _this.diary.title = response.data.data.title;
          _this.diary.content = response.data.data.content;
          if(response.data.data.picture_urls.length != 0){  //拿到了图片信息时，
            _this.imageUrl = 'http://oneday.vaiwan.com' + response.data.data.picture_urls;
            //console.log(_this.imageUrl);
          }else{
            _this.imageUrl = '';
          }

      	}).catch(function(error){
      	  alert("请重新登录！");
      	  _this.$router.push("/");
      	});
        }else{  //如果拿不到did和state，说明是新建日记，给title,content和editTime赋空值，给did赋值0发给后端用作新建
          _this.diary.title = "";
          _this.diary.content = "";
          _this.diary.editTime = "";
          _this.diary.did = 0;
          _this.imageUrl = '';
        };
        _this.imgDid.did = _this.diary.did;
         console.log(_this.imgDid);
    	},

      beforeAlbumUpload(file) { //限制文件格式
          const isJPG = file.type === 'image/jpeg';
          const isLt2M = file.size / 1024 / 1024 < 2;

          if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 格式!');
          }
          if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
          }
          return isJPG && isLt2M;
      },
      handleAlbumSuccess(res, file) {
          // res表示后端的返回值，其中应包含文件上传后的url路径
          console.log(res);
          // file表示这个上传文件本身
          console.log(file);
          // 不是很清楚这个URL创建的方法，应该是文件展示的一种方式
          // this.imageUrl = URL.createObjectURL(file.raw);
          // 此处可以将上传成功的文件url赋值给image的src属性，一般为相对路径，需要拼接为完整的url
          this.imageUrl = 'http://oneday.vaiwan.com' + res.data;
          //console.log(imageUrl);
      }



  },
 }
</script>

<style>

</style>
